package com.movecar.utils;

import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;

import android.content.Context;
import android.widget.ArrayAdapter;

import com.amap.api.location.core.GeoPoint;
import com.baidu.location.BDLocation;

public final class Converter {

	private static float density;

	/**
	 * 将dp单位转换为实际px单位。
	 * 
	 * @since 1.0.1
	 */
	public static int dp2pixel(final Context context, final int dp) {
		return (int) Math.ceil(dp * Converter.getDensity(context));
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	private static float getDensity(final Context context) {
		if (Converter.density == 0)
			return Converter.density = context.getResources().getDisplayMetrics().density;
		return Converter.density;
	}

	/**
	 * 将定位位置转换为GPS位置。
	 * 
	 * @author Sun Fulong
	 * @since 1.0.1
	 */
	public static GeoPoint locationToGeoPoint(final BDLocation location) {
		return new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
	}

	@SuppressWarnings("unchecked")
	public static <T> T[] arrayAdapterToArray(final ArrayAdapter<T> adapter) {
		final int length = adapter.getCount();
		final ArrayList<T> list = new ArrayList<T>(length);
		for (int i = 0; i < length; i += 1) {
			list.add(adapter.getItem(i));
		}
		return list.toArray((T[]) Array.newInstance((Class<T>) ((ParameterizedType) adapter.getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0], length));
	}

	private static String TASK_NAME_SUFFIX = "Task";
	private static String RECEIVER_NAME_SUFFIX = "Receiver";
	private static String CALLBACK_METHOD_NAME_SUFFIX = "Callback";
	private static String RECEIVE_METHOD_NAME_SUFFIX = "Receive";

	public static String taskClassNameToCallbackMethodName(final String className) {
		return Converter.classNameToMethodName(className, Converter.TASK_NAME_SUFFIX,
				Converter.CALLBACK_METHOD_NAME_SUFFIX);
	}

	public static String receiverClassNameToReceiveMethodName(final String className) {
		return Converter.classNameToMethodName(className, Converter.RECEIVER_NAME_SUFFIX,
				Converter.RECEIVE_METHOD_NAME_SUFFIX);
	}

	private static String classNameToMethodName(final String className, final String suffixFrom, final String suffixTo) {
		final StringBuilder result = new StringBuilder(className.length() - suffixFrom.length() + suffixTo.length());
		result.append(className);
		result.replace(0, 1, Character.toString(Character.toLowerCase(result.charAt(0))));
		result.delete(result.length() - suffixFrom.length(), result.length());
		result.append(suffixTo);
		return result.toString();
	}
}
